package net.runman.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import net.runman.core.security.AppUserDetailService;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private AppUserDetailService appUserDetailService;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers(
				"/static/**", 
				"/404.html", "/500.html",
				"/", "/index.html",
				"/admin/sign-in.html"
			).permitAll()
			.antMatchers(
				"/admin/**"
			).authenticated();
		http.formLogin()
			.loginPage("/admin#!/admin/sign-in.html")
			.loginProcessingUrl("/admin")
			.usernameParameter("username")
			.passwordParameter("password")
			.failureUrl("/login.html?error")
			.defaultSuccessUrl("/index.html")
			.permitAll();
		http.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout.html"))
			.logoutSuccessUrl("/index.html")
			.deleteCookies("uid");
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(appUserDetailService).passwordEncoder(new BCryptPasswordEncoder());
	}

}